from django.db import models

# 使用我们自己的QuerySet来管理各种操作 BaseManager.from_queryset(LyQuerySet)
class CustomManager(models.Manager):
    def __init__(self, *args, **kwargs):
        self.__add_is_del_filter = True
        super(CustomManager, self).__init__(*args, **kwargs)

    def get_queryset(self, *args, **kwargs):
        queryset = super(CustomManager, self).get_queryset(*args, **kwargs)

        if self.__add_is_del_filter:
            queryset = queryset.filter(is_delete=False)
        return queryset

    def filter(self, *args, **kwargs):
        # 考虑是否主动传入is_delete
        if not kwargs.get('is_delete') is None:
            self.__add_is_del_filter = False
        return super(CustomManager, self).filter(*args, **kwargs)

class BaseModel(models.Model):
    objects = CustomManager()
    # objects = models.Manager()
    objects_old = models.Manager()  # 原始的用法

    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除', help_text='逻辑删除')
    sort = models.IntegerField("排序", default=1, blank=True, null=True)

    createTime = models.DateTimeField('创建日期', auto_now_add=True, blank=True, null=True)
    updateTime = models.DateTimeField('更新日期', blank=True, null=True)
    deleteTime = models.DateTimeField('删除日期', blank=True, null=True)

    createUser = models.ForeignKey('user.UserModel', related_name="%(app_label)s_%(class)s_related",
                                   verbose_name='创建账号', on_delete=models.SET_NULL, null=True, blank=True,
                                   db_constraint=False)
    createUsername = models.CharField("创建人", max_length=200, blank=True, null=True, default='')

    class Meta:
        abstract = True

    # 子类中判断实例是否存在时使用
    def DoesNotExist(self):
        return self.DoesNotExist
